from django.shortcuts import render, HttpResponse, reverse
import random
from utils.tencent.sms import send_sms_single
from django.conf import settings
from app01.forms import RegisterModelForm
from app01 import models
from django.http.response import JsonResponse
import redis
import re


# Create your views here.

def send_sms(request):
    tpl = request.GET.get('tpl')
    template_id = settings.TENCENT_SMS_TEMPLATE.get(tpl)
    code = random.randrange(100000, 999999)
    if not template_id:
        return HttpResponse('模板不存在')
    if template_id == 552568:
        res = send_sms_single('15969681925', template_id, [code, 1])
    else:
        res = send_sms_single('15969681925', template_id, [code, ])
    if res['result'] == 0:
        return HttpResponse('成功')
    else:
        return HttpResponse(res['errmsg'])


def register(request):
    form_obj = RegisterModelForm()
    if request.method == 'POST':
        form_obj = RegisterModelForm(request.POST, request.FILES)
        if form_obj.is_valid():
            # form_obj.save()
            # return RegisterModelForm(reverse('login'))
            return HttpResponse('注册成功')
        print(form_obj.cleaned_data)

    return render(request, 'app01/register.html', locals())


def code_phone(request):
    form = RegisterModelForm()
    mobile_phone = request.GET.get('mobile_phone')
    verify_code = random.randrange(100000, 999999)
    print(mobile_phone, verify_code)
    if re.match(r'^1[3-9]\d{9}$', mobile_phone):

        # 连接redis
        conn = redis.Redis(host='localhost', port=6379, password='foobared', encoding='utf-8')
        # 设置键值：15969681925="9999" 且超时时间为10秒（值写入到redis时会自动转字符串）
        conn.set(mobile_phone, verify_code, ex=60)
        # 根据键获取值：如果存在获取值（获取到的是字节类型）；不存在则返回None
        # value = conn.get(mobile_phone)
        # print(value)
        res = send_sms_single(mobile_phone, settings.TENCENT_SMS_TEMPLATE.get('register'), [verify_code, 1])
        if res['result'] == 0:
            return JsonResponse({'status': True, 'mobile_phone': mobile_phone, 'verify_code': verify_code})

    return JsonResponse({'status': False, 'error': form.errors})
